<template>
  <div class="home">
    <div class="header-contant">
      <img :src="userinfo.avatar" class="avatar">
      <div class="main-contant">
        <div class="row">
          <div class="name">{{userinfo.nickname}}</div>
          <div class="clesius">{{weatherInfo.diwen}}~{{weatherInfo.gaowen}}</div>
        </div>
        <div class="row">
          <div class="money">
            余额
            <span>{{userinfo.all_balance}}</span> 元
          </div>
          <div class="area">{{cityName.length<=0?'定位中':cityName}} {{weatherInfo.tianqi}}</div>
        </div>
      </div>
      <img :src="weather" class="weather">
      <div class="search-contant">
        <div class="search-box">
          <div class="city" @click="showNav">
            <div class="city-name">{{cityName.length<=0?'定位中':cityName}}</div>
            <i class="iconfont icon-xiangxia arrow" style="font-size:0.1rem;"></i>
          </div>
          <input class="input-contant" @blur="inputBack()" v-model="title">
          <i
            class="iconfont icon-shoucangdedian star"
            style="font-size:0.5rem;"
            @click="jumpPathTo('/Collections')"
          ></i>
          <div class="button-contant" @click="getList()">
            <i class="iconfont icon-sousuo" style="font-size:0.5rem;"></i>
          </div>
        </div>
      </div>
    </div>
    <div class="show-contant" ref="wrapper">
      <div class="show-scroll-contant">
        <div class="space"></div>
        <div
          class="item-contant"
          v-for="(item,index) in List"
          :key="index"
          @click="jumpTo(item.id)"
          :style="item.online == 0?'opacity:0.4;':'opacity:1'"
        >
          <div class="item-header-contant">
            <div class="name-contant">{{item.title}}</div>
            <i class="iconfont icon-juli" style="font-size:0.4rem;"></i>
            <span>{{item.distance}}KM</span>
          </div>
          <div class="item-middle-contant">
            <div class="text-contant">{{item.address}}</div>
            <div class="number-contant">
              共
              <span>{{item.num}}</span> 个插头
            </div>
          </div>
          <div class="item-bottom-contant">
            <div class="item-status-contant">
              <div class="status-contant">
                <span class="one">闲</span>
                <span class="num">{{item.num-item.charging_num}}</span>
              </div>
              <div class="status-contant">
                <span class="two">充</span>
                <span class="num">{{item.charging_num}}</span>
              </div>
            </div>
            <div class="elc-contant">
              <Power :number="item.sign" :color="true"></Power>
            </div>
          </div>
          <i class="iconfont icon-dizhi title-icon"></i>
        </div>
        <div class="notdata" v-if="List.length<=0">
          <img :src="nothing">
          <div class="text">此地区暂无信息</div>
        </div>
      </div>
      <div class="cover-contant" v-show="cityShow"></div>
    </div>
    <div class="city-contant" v-show="cityShow">
      <div class="city-box">
        <div class="city-nav" ref="nav">
          <div>
            <div
              class="province-item-box"
              v-for="(item,index) in cityTotalList"
              :key="index"
              @click="chooseProvince(item.id,index)"
            >
              <div
                :class="'item-contant'+ (item.id == provinceID ? ' highlight':' normal')"
              >{{item.province}}</div>
            </div>
          </div>
        </div>
        <div class="city-menu" ref="city">
          <div>
            <div class="city-item-contant" v-for="(item,index) in cityList" :key="index">
              <div
                :class="'city-item-box'+ (item.id == cityID?' highlight':' normal2')"
                @click="chooseCity(item.id,item.city)"
              >
                <div class="name">{{item.city}}</div>
                <img :src="gou" class="check-icon" v-if="item.id == cityID">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
@import "index.less";
</style>

<script>
import { mapActions, mapState } from "vuex";
import Power from "../../components/power/index";
import BScroll from "better-scroll";
import wx from "weixin-js-sdk";
export default {
  name: "home",
  data() {
    return {
      avatar: require("../../assets/person/avatar.png"),
      weather: require("../../assets/weather/1.png"),
      gou: require("../../assets/public/gou.png"),
      nothing: require("../../assets/nothing.png"),
      // 后台
      userinfo: {}, // 用户数组
      cityTotalList: [], // 城市总列表,
      cityList: [], // 当前显示的城市列表
      provinceID: "",
      cityName: "", // 当前显示的名字
      cityID: 0,
      List: {}, // 充电桩列表
      page: 1, // 当前组件页数
      cityShow: false,
      // 控制组件
      listScroll: {}, // 车充电桩详情滑动
      provinceScroll: {}, // 省滑动
      lock: false,
      title: "", // 查询文字
      // 天气组件
      weatherInfo: {},
      weatherArr: [
        {
          name: "晴天",
          img: require("../../assets/weather/1.png")
        },
        {
          name: "大雨",
          img: require("../../assets/weather/2.png")
        },
        {
          name: "暴雨",
          img: require("../../assets/weather/3.png")
        },
        {
          name: "下雪",
          img: require("../../assets/weather/4.png")
        },
        {
          name: "阵雨",
          img: require("../../assets/weather/5.png")
        },
        {
          name: "多云",
          img: require("../../assets/weather/6.png")
        },
        {
          name: "阵雨",
          img: require("../../assets/weather/7.png")
        },
        {
          name: "多云",
          img: require("../../assets/weather/8.png")
        }
      ],
      // 地理信息
      geography: {},
      setIn: true //扫码防止循环
    };
  },
  components: {
    Power
  },
  methods: {
    ...mapActions("Home", ["change"]),
    ...mapActions("Person", ["setPerson"]),
    ...mapActions("Setting", ["setScale", "setLoc"]),
    // 页面组件
    // 控制选择器显示
    selectWeather(name) {
      const target = this.weatherArr.find(f => f.name == name);
      if (target) {
        this.weather = target.img;
      }
    },
    showNav() {
      if (this.cityShow) {
        this.cityShow = false;
      } else {
        this.cityShow = true;
      }
    },
    // 滑块init
    scrollInit() {
      // 更新滑动组件
      this.listScroll = new BScroll(this.$refs.wrapper, {
        click: true,
        pullUpLoad: {
          threshold: -50
        }
      });
      // 上拉加载更多
      this.listScroll.on("pullingUp", () => {
        if (this.lock) {
          return;
        }
        // 页数加一
        this.page++;
        // 锁定防止多次加载
        this.lock = true;
        this.$dialog.loading.open("正在加载");
        this.$http
          .get("/device/List", {
            params: {
              page: this.page,
              lng: this.geography.longitude,
              lat: this.geography.latitude,
              title: this.title,
              city: this.cityName
            }
          })
          .then(res => {
            // 请求回来的数据相加
            this.List = this.List.concat(res.data.data);
            if (res.data.data.length <= 0) {
              this.$dialog.toast({
                mes: "没有更多的数据",
                timeout: 1500,
                icon: "none"
              });
              this.lock = true;
            } else {
              // 解锁上拉
              this.lock = false;
            }
            this.$forceUpdate();
            this.listScroll.finishPullUp();
            this.listScroll.refresh();
            this.$dialog.loading.close();
          });
      });
      this.$forceUpdate();
    },
    // 省滑动
    navInit() {
      this.provinceScroll = new BScroll(this.$refs.nav, {
        click: true
      });
    },
    // 市滑动
    cityInit() {
      this.provinceScroll = new BScroll(this.$refs.city, {
        click: true
      });
    },
    // 点击获取省的ID
    chooseProvince(id, index) {
      this.provinceID = id;
      // 更新展示的城市列表
      this.cityList = this.cityTotalList[index].city;
      // 更新市滑块
      this.cityInit();
    },
    // 点击选取城市
    chooseCity(id, name) {
      this.cityID = id;
      this.cityName = name;
      this.cityShow = false;
      this.getList();
    },
    // 后台请求
    // 获取用户信息
    getUser() {
      this.$http.get("/user/Info", {}).then(res => {
        if (res.data.errno == 0) {
          this.userinfo = res.data.data;
          this.setPerson(res.data.data);
          // 授权接口
          this.WXconfig();
          // 获取城市列表
          this.getCityList();
        } else {
          this.$router.push("/login");
        }
      });
    },
    // 获取充电桩
    getList() {
      const that = this;
      wx.getLocation({
        type: "wgs84", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
        success: function(res) {
          console.log(res);
          var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
          var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
          //   var speed = res.speed; // 速度，以米/每秒计
          //   var accuracy = res.accuracy; // 位置精度
          that.geography = res;
          that.setLoc(res);
          console.log(that.geography, "测试");
          // 获取展示系列表
          that.page = 1;
          that.$dialog.loading.open("正在加载");
          that.$http
            .get("/device/List", {
              params: {
                page: that.page,
                lng: longitude,
                lat: latitude,
                title: that.title,
                city: that.cityName
              }
            })
            .then(res => {
              // 如果当前页面是加载第一页
              that.List = res.data.data;
              that.$dialog.loading.close();
              that.scrollInit();
              if (that.cityName == "") {
                that.updateCity();
              }
            });
        }
      });
    },
    // 更新城市名字
    updateCity() {
      const that = this;
      let citylocation = new qq.maps.CityService();
      citylocation.setComplete(function(result) {
        let detail = result.detail.detail;
        let res = detail.split(",");
        that.cityName = res[1];
        // 获取天气
        that.getWeather();
      });
      citylocation.searchCityByLatLng(
        new qq.maps.LatLng(that.geography.latitude, that.geography.longitude)
      );
    },
    // 获取市区列表
    getCityList() {
      this.$http
        .get("/city/List", {
          params: {}
        })
        .then(res => {
          this.cityTotalList = res.data.data;
          // 更新滑块
          this.navInit();
          // 选取第一位
          this.provinceID = this.cityTotalList[0].id;
          this.cityList = this.cityTotalList[0].city;
          this.cityID = this.cityTotalList[0].city[0].id;
        });
    },
    // 获取天气
    getWeather() {
      this.$http
        .get("/weather", {
          params: {
            city: this.cityName
          }
        })
        .then(res => {
          this.weatherInfo = res.data.data;
          this.selectWeather(this.weatherInfo.tianqi);
        });
    },
    // vue内部
    // 跳转
    jumpTo(ID) {
      this.$router.push({
        path: "/Stations",
        query: {
          devID: ID
        }
      });
    },
    jumpPathTo(path) {
      this.$router.push({
        path: path
      });
    },
    WXconfig() {
      const that = this;
      this.$http
        .get("/wechat_jssdk", {
          params: {
            url: window.location.href
          }
        })
        .then(res => {
          const result = res.data.data;
          wx.config({
            debug: false,
            appId: result.appId, // 和获取Ticke的必须一样------必填，公众号的唯一标识
            timestamp: result.timestamp, // 必填，生成签名的时间戳
            nonceStr: result.nonceStr, // 必填，生成签名的随机串
            signature: result.signature, // 必填，签名，见附录1
            //需要分享的列表项:发送给朋友，分享到朋友圈，分享到QQ，分享到QQ空间
            jsApiList: [
              "checkJsApi",
              "startRecord",
              "stopRecord",
              "translateVoice",
              "scanQRCode",
              "openCard",
              "updateAppMessageShareData",
              "getLocation",
              "openLocation",
              "chooseImage",
              "uploadImage",
              "getLocalImgData",
              "downloadImage"
            ]
          });
          wx.ready(() => {
            // 获取列表
            that.getList();
            // 判断
            that.rejudeScale();
          });
        });
    },
    // 判断是否为扫码扫进来
    rejudeScale() {
      if (this.scaleIn) {
        if (this.$route.query.type || this.$route.query.id) {
          this.setScale(false);
          this.$router.push({
            path: "/Pay",
            query: {
              id: this.$route.query.id
            }
          });
        }
      }
    }
  },
  created() {
    // 是否展示菜单
    this.change(true);
    // 获取用户信息
    this.getUser();
  },
  mounted() {},
  computed: {
    ...mapState({
      scaleIn: state => state.Setting.scaleIn
    })
  }
};
</script>
